<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : WechatApp.php
 * Created on : 2021-2-4 16:26:04
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace app\wechat\model;

use think\Model;
use app\wechat\model\WechatAppAddons;

/**
 * 微信小程序模型
 * Class WechatApp
 * Tiger <1192851302@qq.com> 2021-2-4 16:26:04
 */
class WechatApp extends Model {

    /**
     * 获取数据列表-分页
     * @author Tiger <1192851302@qq.com>
     * @param array $where
     * @return array
     */
    public static function getList($where) {
        $model = self::alias('miniapp')->join('admin_user user', 'user.id= miniapp.uid');
        if (!empty($where['name'])) {
            $model = $model->where('name', 'LIKE', '%' . $where['name'] . '%');
            unset($where['name']);
        }
        if (!empty($where['username'])) {
            $model = $model->where('username', 'LIKE', '%' . $where['username'] . '%');
            unset($where['username']);
        }
        $models = $model->where($where)->field(['miniapp.*', 'user.username'])->order('id desc')->paginate(input('limit', 10))->each(function($item) {
            if ($item->addon) {
                $item->addon_info = WechatAppAddons::where(['addon' => $item['addon']])->find();
                $item->addon_info->admin_url = (string) url('/wechat/app/console/' . $item->addon . '/' . $item->id)->domain(true);
            }
        });
        return [
            'code' => 0,
            'items' => $models->items(),
            'total' => $models->total()
        ];
    }

    /**
     * 
     * @author Tiger <1192851302@qq.com>
     * @param type $mid
     * @return type
     */
    public static function validWhere($mid) {
        return self::where('is_del', 0)->where('status', 1)->where('id', $mid);
    }

    /**
     * 获取单个配置
     * @author Tiger <1192851302@qq.com>
     * @param int $mid
     * @param string $key
     * @return string
     */
    public static function getOne($mid, $key) {
        return self::validWhere($mid)->value($key);
    }

    /**
     * 获得多个参数
     * @author Tiger <1192851302@qq.com>
     * @param int $mid
     * @param string $keys
     * @return array
     */
    public static function getMore($mid, $keys = '*') {
        $data = self::validWhere($mid)->field($keys)->find()->toArray();
        if (empty($data)) {
            exception('应用不存在');
        }
        return $data;
    }

}
